﻿using System.Net.Http.Headers;
using anydata.Entitys;
using anydata.Handlers;

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.IdentityModel.Tokens;

using Newtonsoft.Json.Linq;
using System.Text;


namespace anydata.Controllers
{
    [ApiController]
    [Route("orginone/anydata/[controller]/[action]")]
    public class PublicController : ControllerBase
    {
        readonly DataProvider _provider;
        public PublicController(DataProvider provider)
        {
            _provider = provider;
        }
        [HttpPost()]
        public Task<IActionResult> CreateOrderAsync(TokenModel _token, [FromBody] MallOrderData data)
        {
            return _provider.CreateOrderAsync(_token, data).TryExecuteResult();
        }
        [HttpPost()]
        public async Task<IActionResult> HttpForwardAsync(TokenModel _token, [FromBody] HttpRequestType req)
        {
            HttpClient client = new HttpClient();
            client.Timeout = TimeSpan.FromMinutes(1);
            client.DefaultRequestHeaders.Add("User-Agent", "orginone");
            var uri = new Uri(req.Uri);
            var request = new HttpRequestMessage();
            request.Headers.Host = uri.Authority;
            request.RequestUri = uri;
            request.Method = new HttpMethod(req.Method);
            request.Content = new StringContent(req.Content);
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            foreach (KeyValuePair<string, string> kvp in req.Header)
            {
                if (kvp.Key == "Content-type")
                {
                    request.Content.Headers.ContentType = new MediaTypeHeaderValue(kvp.Value);
                }
                else
                {
                    request.Headers.Add(kvp.Key, kvp.Value);
                }
            }
            var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            if (response != null)
            {
                var contentType = "";
                if (response != null && response.Headers.TryGetValues("Content-type", out IEnumerable<string>? values))
                {
                    contentType = values.First();
                }
                return OperateResult.Success(new
                {
                    contentType,
                    status = response!.StatusCode,
                    header = response!.Headers,
                    content = await response!.Content.ReadAsStringAsync(),
                }).Result();
            }
            return OperateResult.Faild("转发失败!").Result();
        }
    }
}
